package week_07;

public class SurroundedRegions_dfs_130 {
    int[] dx = new int[]{-1, 0, 0, 1};
    int[] dy = new int[]{0, -1, 1, 0};
    int[] fa;
    int m;
    int n;
    boolean[][] isVisit;

    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;
        isVisit = new boolean[m][n];
        fa = new int[m * n + 1];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                fa[num(i, j)] = num(i, j);
            }
        }
        fa[n * m] = m * n;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                isVisit[i][j] = true;
                dfs(board, i, j);
            }
        }
        // 分好并查集块
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O' && get(num(i, j)) != get(m * n)) {
                    board[i][j] = 'X';
                }
            }
        }

    }

    public void dfs(char[][] board, int i, int j) {
        if (board[i][j] == 'X') return;
        if (i == 0 || j == 0 || i == m - 1 || j == n - 1) fa[get(num(i, j))] = get(m * n);
        for (int k = 0; k < 4; k++) {
            int nx = i + dx[k];
            int ny = j + dy[k];
            // 走一步就越界 说明x,y 就是边部点
            if((i==1&&j==1)||(nx==1&&ny==1)){
                System.out.println("_____");
            }
            if (nx < 0 || ny < 0 || nx >= m || ny >= n) continue;
            if (isVisit[nx][ny]) continue;
            isVisit[nx][ny] = true;

            if (board[nx][ny] == 'O') {
                fa[get(num(nx, ny))] = get(num(i, j));
            }
            dfs(board, nx, ny);
        }
    }

    public int get(int x) {
        return x == fa[x] ? x : (fa[x] = get(fa[x]));
    }

    public int num(int i, int j) {
        return i * n + j;
    }

    public static void main(String[] args) {
        char[][] board = {{'O', 'O', 'O'}, {'O', 'O', 'O'}, {'O', 'O', 'O'}};
        SurroundedRegions_dfs_130 test=new SurroundedRegions_dfs_130();
        test.solve(board);
    }
}
